﻿using AngleSharp;
using AngleSharp.Html.Dom;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace HttpDownload
{
    class Program
    {
        static IHttpClientFactory _httpClientFactory;

        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                .AddHttpClient()
                .BuildServiceProvider();
            _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

            var config = Configuration.Default.WithDefaultLoader();
            var html = BrowsingContext.New(config).OpenAsync("https://www.oschina.net/").Result;
            var img = html.QuerySelector("figure.figure img") as IHtmlImageElement;

            var result = DownloadFile(img.Source);
            if (result.Result)
                Console.WriteLine("文件下载完成.");
            else
                Console.WriteLine("文件下载失败.");

            Console.ReadKey();
        }

        static async Task<bool> DownloadFile(string fileUrl)
        {
            try
            {
                var http = _httpClientFactory.CreateClient();
                var response = await http.GetAsync(fileUrl);

                if (!Directory.Exists("download"))
                {
                    Directory.CreateDirectory("download");
                }

                var uri = new Uri(fileUrl);
                var filename = Path.Combine("download", Path.GetFileName(uri.LocalPath));
                using var file = File.Create(filename);
                await response.Content.CopyToAsync(file);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }
    }
}
